<?php
/**
 * 申领单 ajax类
 * @package  ajax
 * @subpackage  company
 * @author   create by allen.qiang
 */

quanli_require('module/base/company/cardApply.class.php');
quanli_require('module/base/system/sysUser.class.php');
quanli_require('module/base/system/sysDepartment.class.php');

class ajax_cardApply{

    public function execute() {

        if(isset($_REQUEST['operFlg']) && quanli_is_int($_REQUEST['operFlg'])){

            switch($_REQUEST['operFlg']){

                case 1://申领单列表
                    $this->cardApplyList();
                    break;

                case 2://申领单查询
                    $this->searchcardApply();
                    break;

                case 3://查询现金卡新增信息
                    $this->searchCardAdd();
                    break;

                case 4: //申领单发卡，检查卡号
                    $this->checkCardNo();
                    break;

                case 6: //审核申领单
                    $this->auditCard();
                    break;

                case 7://申领单发卡
                    $this->tuckCard();
                    break;

                case 8://申领单开票
                    $this->outInvoiceCard();
                    break;

                case 9: //确认开票
                    $this->confirmInvoice();
                    break;

                case 10://查询申领人
                    $this->searchSaler();
                    break;

                case 11://申领单回款
                    $this->returnedMoney();
                    break;

                case 12://确认回款
                    $this->confirmReturned();
                    break;

                case 13://申领单详情
                    $this->tuckCardDetails();
                    break;
                case 14://删除回款单
                    $this->delReturned();
                    break;

                case 100:

                    if (!isset($_REQUEST['act']) || !in_array($_REQUEST['act'], array('del', 'edit'))) {

                        returnJsonData('参数错误');

                    }

                    if ($_REQUEST['act'] == 'edit') {

                        $this->edit();//新增、修改 申领单

                    } else if ($_REQUEST['act'] == 'del') {

                        $this->deleteCardApply();//删除申领单

                    }

                    break;

                default:

                    returnJsonData('参数错误');

                    break;
            }

        }else {
            returnJsonData('参数错误');
        }
    }


    /**
     * 申领单列表
     */
    private function cardApplyList(){

        global $G_SHOP;

        //获得用户的所属部门及以下部门
        $PS_LOGIN_SESSION =$G_SHOP->sessionCache_get('PS_LOGIN_SESSION');
        $departmentID = $PS_LOGIN_SESSION['department'];//当前部门id

        //实例化部门类
        $sysDepartment = new sysDepartment();

        //部门数据
        $department_array = array();
        //递归查询部门数据
        $sysDepartment->searchDepartment( $department_array,0,-1,$departmentID);

        //递归获得多维数组索引的方法（部门id）的方法
        function getKey( $array , &$foreachKey_array){

            if( is_array( $array )){
                foreach( $array as $k=>$v){
                    if( $k == "departmentID"){
                        $foreachKey_array[] = $v;
                    }

                    if( is_array( $v )){
                        getKey( $v, $foreachKey_array );
                    }
                }
            }
        }


        $departmentKeyArray = array();
        getKey( $department_array, $departmentKeyArray );

        if( !empty($departmentKeyArray) ) { //当前登录用户权限下部门
            $str_departmentID = implode( ',',$departmentKeyArray );
            $_REQUEST['extend'] = " AND departmentID IN (".$str_departmentID.")";
        } else { //当前登录用户没有任何所属部门
            //组织返回的数据
            $result_array = array(
                'page' => 1,
                'total' => 0,
                'rows' => array()
            );
            echo json_encode($result_array);
        }

        //实例化申领单信息类
        $cardApply = new cardApply();
        if( isset( $_REQUEST['search_departmentID']) && !empty($_REQUEST['search_departmentID'])){
           // $_REQUEST['departmentID'] = $_REQUEST['search_departmentID'];
            if($_REQUEST['search_departmentID']!=""){

                $department_arrays = array();
                //实例化部门类
                $sysDepartments = new sysDepartment();
                //递归查询部门数据
                $sysDepartments->searchDepartment( $department_arrays,0,-1,$_REQUEST['search_departmentID']);
                $departmentKeyArrays= array();
                getKey( $department_arrays, $departmentKeyArrays );
                $str_departmentIDs = implode( ',',$departmentKeyArrays );

                $_REQUEST['departmentID'] =$str_departmentIDs;

            }else{
                $_REQUEST['departmentID'] = $_REQUEST['search_departmentID'];
            }
        }
        if(isset($_REQUEST['invoice_no']) && !empty($_REQUEST['invoice_no']))
        {

            $apply_invoice_array = $G_SHOP->DBCA->stmt_query("select * from card_apply_invoice where invoice_no = ? limit 1", "i", $_REQUEST['invoice_no']);

            if($apply_invoice_array && $_REQUEST['invoice_no'] == $apply_invoice_array[0]->invoice_no)
            {

                $_REQUEST['apply_id'] = $apply_invoice_array[0]->apply_id;
            }
            else
            {
                $_REQUEST['apply_id'] = "999999999";
            }

        }



        $_REQUEST['is_delete'] = 1;
        $arg_array = $_REQUEST;
        $result = $cardApply->search( $arg_array );

        //组织返回的数据
        $result_array = array(
            'page' => $arg_array['page'],
            'total' => $arg_array['count'],
            'rows' => array()
        );

//        if (isset($_REQUEST['list_type']) && $_REQUEST['list_type'] == 'general') {
//
//            $result_array['data'] = $result;
//            if ($result) {
//                $result_array['paging'] = shop_page($arg_array['page'], $arg_array['count'], $arg_array['rp'], 'javascript: cardApplyList.search(%d);', $G_SHOP->smarty, 'comm/page.tpl');
//            }
//
//        }else{
            if ($result) {

                $edit_permission = $G_SHOP->has_permission(70005);

                foreach($result as &$data) {

                    $get_card_type="";
                    if( $data['get_card_type'] == 1 ){
                        $get_card_type = '个人';
                    }elseif ( $data['get_card_type'] == 2 ){
                        $get_card_type = '公司';
                    }

                    $status ="";
                    if($data['status'] == 1){
                        $status = "申请中";
                    }elseif ($data['status'] == 2){
                        $status = "已审核";
                    }elseif ($data['status'] == 3){
                        $status = "已发卡";
                    }

                    $invoice_status ="";
                    if($data['invoice_status'] == 0){
                        $invoice_status = "未开票";
                    }elseif($data['invoice_status'] == 1){
                        $invoice_status = "部分开票";
                    }else{
                        $invoice_status = "全部开票";
                    }

                    $returned_money_status ="";
                    if($data['returned_money_status'] == 0){
                        $returned_money_status = "未回款";
                    }elseif($data['returned_money_status'] == 1){
                        $returned_money_status = "部分回款";
                    }else{
                        $returned_money_status = "全部回款";
                    }
                    //创建人号码
//                    $userSql="SELECT mobile FROM user_master where creator= ? ";
//                    $userArray=$G_SHOP->DBCA->stmt_query($userSql,'s',$data['creator']);
//                    $mobile=$userArray[0]->mobile;
                    //error_log(print_r($mobile,1));


                    if ($edit_permission) {

                        $operation_html = '';
                        $sudit="";
                        if ( $data['status'] == 1){ 

                            $operation_html .= '<a href="javascript:void(0);" onclick="cardApplyList.edit(' . $data['apply_id'] . ');">修改</a>&nbsp;&nbsp;';

                            if($G_SHOP->has_permission(70009)){
                                $sudit="OK";
                                $operation_html .= '<a href="javascript:void(0);" onclick="cardApplyList.audit(' . $data['apply_id'] . ');">审核</a>&nbsp;&nbsp;';
                                //申领单不符合条件 短息通知销售员
                                if(isset($data['apply_mobile']) && !empty($data['apply_mobile']) && $data['apply_mobile']!="")
                                {
                                    $operation_html .= '<a href="javascript:void(0);" onclick="cardApplyList.display(' .$data['apply_mobile'] . ');">短信通知</a>&nbsp;&nbsp;';
                                }
                                else
                                {
                                    $operation_html .= '<a href="javascript:void(0);" onclick="alert('."'未填写手机'".');">短信通知</a>&nbsp;&nbsp;';
                                }

                            }
                            if($G_SHOP->has_permission(70010)){
                                $operation_html .= '<a href="javascript:void(0);" onclick="cardApplyList.del(' . $data['apply_id'] . ');">删除</a>&nbsp;&nbsp;';
                            }

                        } elseif ( $data['status'] == 2 ) {
                            //对已审核的申领单也增加可以修改的入口add by loreta.cheng 2015-06-15 start
                            if($G_SHOP->has_permission(70017)){
                                $operation_html .= '<a href="javascript:void(0);" onclick="cardApplyList.edit(' . $data['apply_id'] . ');">修改</a>&nbsp;&nbsp;';
                            }
                            //对已审核的申领单也增加可以修改的入口add by loreta.cheng 2015-06-15 end
                            if($G_SHOP->has_permission(70006)){

                                $operation_html .= '<a href="javascript:void(0);" onclick="cardApplyList.tuck.open(' . $data['apply_id'] . ');">发卡</a>&nbsp;&nbsp;';
                            }
                        } elseif ($data['status'] == 3){

                            if($G_SHOP->has_permission(70007)){

                                $operation_html .= '<a href="javascript:void(0);" onclick="cardApplyList.out.invoice(' . $data['apply_id'] . ');">开票</a>&nbsp;&nbsp;';

                            }
                            if($G_SHOP->has_permission(70011)){

                                $operation_html .= '<a href="javascript:void(0);" onclick="cardApplyList.returned.money(' . $data['apply_id'] . ');">回款</a>&nbsp;&nbsp;';
                            }
                        }
                        $operation_html .= '<a href="javascript:void(0);" onclick="cardApplyList.look(' . $data['apply_id'] . ');">查看</a>';
                        $apply_id_html='<a href="javascript:void(0);" onclick="cardApplyList.look(' . $data['apply_id'] . ',\''.$sudit.'\');">'. $data['apply_id'].'</a>';

                        $result_array['rows'][] = array (
                            'id' => $data['apply_id'],
                            'cell' => array(
                                $operation_html,
                                $apply_id_html,
                                $data['apply_date'],
                                $get_card_type,
                                $data['customer_name'],
                                $data['linkman'],
                                $data['contact_way'],
                                $data['departmentName'],
                                $returned_money_status,
                                $data['statusKp']==1?'开票申请':'',
                                $data['card_total_num'],
                                $data['apply_trueName'],
                                $data['total_amount'],
                                $data['paymentName'],
                                $data['send_card_time'],
                                $status,
                                $invoice_status,
                                $data['remark']


                            )
                        );

                    } else {

                        $operation_html = '';
                        $result_array['rows'][] = array (
                            'id' => $data['apply_id'],
                            'cell' => array(
                                $operation_html,
                                $apply_id_html,
                                $data['apply_date'],
                                $get_card_type,
                                $data['customer_name'],
                                $data['linkman'],
                                $data['contact_way'],
                                $data['departmentName'],
                                $returned_money_status,
                                $data['card_total_num'],
                                $data['apply_trueName'],
                                $data['total_amount'],
                                $data['send_card_time'],
                                $status,
                                $invoice_status,
                                $data['remark']

                            )
                        );

                    }

                }

//            }
        }

        //error_log(print_r($result_array,1));
        echo json_encode($result_array);
    }


    /**
     * 新增/修改  申领单
     */
    private function edit() {

        global $G_SHOP;

        //实例申领单类
        $cardApply = new cardApply();

        //新增/修改
        $_REQUEST['creator'] = $G_SHOP->currentUserID;
        $result_array = $cardApply->editCardApply( $_REQUEST );

        returnJsonData($result_array['message'], $result_array['code']);

    }


    /**
     * 查询申领单方式
     */
    private function searchcardApply() {

        global $G_SHOP;

        if (!isset($_REQUEST['apply_id']) || !quanli_is_int($_REQUEST['apply_id'])) {
            returnJsonData('参数错误');
        }

        //实例申领单类
        $cardApply = new cardApply();

        //查询申领单方式
        $arg_array = array(
            'apply_id' => $_REQUEST['apply_id']
        );
        $cardApply_array = $cardApply->search( $arg_array );

        if ($cardApply_array) {
            returnJsonData('ok', 200, $cardApply_array[0]);
        } else {
            returnJsonData('申领单信息没有找到', 404);
        }

    }


    /**
     * 查询现金卡新增方式
     */
    public function searchCardAdd(){

        if (!isset($_REQUEST['apply_id']) || !quanli_is_int($_REQUEST['apply_id'])) {
            returnJsonData('参数错误');
        }

        //实例申领单类
        $cardApply = new cardApply();

        //查询申领单方式
        $arg_array = array(
            'apply_id' => $_REQUEST['apply_id']
        );
        $cardApply_array = $cardApply->searchCardApplyDetail( $arg_array );


        if ($cardApply_array) {
            returnJsonData('ok', 200, $cardApply_array[0]);
        } else {
            returnJsonData('现金卡信息没有找到', 404);
        }

    }

    /**
     * 删除申领单信息
     */
    private function deleteCardApply() {

        //实例申领单类
        $cardApply = new cardApply();

        //批量删除申领单信息
        $result_array = $cardApply->deleteCardApply( $_REQUEST );

        returnJsonData( $result_array['message'], $result_array['code'] );

    }

    //审核申领单
    public function auditCard(){

        global $G_PGLOB;

        //调用卡管理类中的审核申领单方法
        $cardApply = new cardApply( $G_PGLOB->DBCA ) ;

        $result_array= $cardApply->auditCardProduct( $_REQUEST['apply_id'] ) ;

        echo json_encode($result_array);

    }

    //申领单发卡
    private function tuckCard(){

        global $G_PGLOB;

        $_REQUEST['operator'] = $G_PGLOB->currentUserID;

        //实例化申领单类
        $cardApply = new cardApply() ;

        $result = $cardApply->tuckCard($_REQUEST);

        returnJsonData($result['message'], $result['code'] );

    }

    /**
     * 申领单发卡，检查卡号
     */
    private function checkCardNo() {

        if (!isset($_REQUEST['apply_id'], $_REQUEST['card_no_start'], $_REQUEST['card_no_end'])) {
            returnJsonData('参数错误');
        }

        if (!quanli_is_int($_REQUEST['apply_id']) || !quanli_is_int($_REQUEST['card_no_start']) || !quanli_is_int($_REQUEST['card_no_end'])) {
            returnJsonData('参数错误');
        }

        quanli_include('module/base/company/cardDetail.class.php');


        //实例金卡详情类
        $cardDetail = new cardDetail();

        //实例申领单类
        $cardApply = new cardApply() ;

        //查询代金卡详情
        $args_array = array(
            'extend' => sprintf(' AND card_no BETWEEN %s AND %s', $_REQUEST['card_no_start'], $_REQUEST['card_no_end'])
        );
        $card_detail_array = $cardDetail->searchCardDetail( $args_array );
        if (!$card_detail_array) {
            returnJsonData('现金卡信息没有找到', 404);
        }

        //现金卡数量
        $card_num = 0;

        $card_num_array = array();
        $apply_card_num_array = array();

        //循环代金卡，检查代金卡状态
        foreach($card_detail_array as &$card_detail) {

            if ($card_detail['card_status'] == 5) {
                returnJsonData(sprintf('代金卡：%s，已发卡', $card_detail['card_no']), 404);
            }
            if ($card_detail['card_status'] == 6) {
                returnJsonData(sprintf('代金卡：%s，已使用', $card_detail['card_no']), 404);
            }
            if ($card_detail['card_status'] == 7) {
                returnJsonData(sprintf('代金卡：%s，已作废', $card_detail['card_no']), 404);
            }

            $card_num_array[$card_detail['card_type']][ (int)( $card_detail['face_value'])]['num'] ++;
            $card_num_array[$card_detail['card_type']][ (int)( $card_detail['face_value'])]['card_no'][] = $card_detail['card_no'];
            $card_num++;
        }

        //查询申领单现金卡详情
        $args_array = array(
            'apply_id' => $_REQUEST['apply_id']
        );
        $apply_card_detail_array = $cardApply->searchCardApplyDetail( $args_array );
        if (!$apply_card_detail_array) {
            returnJsonData('申领单现金卡信息没有找到', 404);
        }

        $err_card_type_array = array();


        foreach($apply_card_detail_array as $apply_card_detail) {
            $apply_card_num_array[$apply_card_detail['card_type_id']][(int)($apply_card_detail['face_value'])] += $apply_card_detail['card_num'] - $apply_card_detail['send_card_num'];
        }


        foreach($card_num_array as $key1=>$card)
        {
            foreach($card as $key2=>$num)
            {
                if( isset($apply_card_num_array[$key1][$key2]))
                {
                    if($apply_card_num_array[$key1][$key2]>=$num['num'])
                    {
                        continue;
                    }
                    else
                    {
                        returnJsonData('录入的代金卡与申领单代金卡数量不匹配', 404);
                        //超数量
                    }
                }
                else
                {
                    $last_str = "";
                    $err_array = array_slice($num['card_no'],0,10)  ;
                    if(count($num['card_no'])>10)
                    {
                        $last_str = ",.....";
                    }

                    returnJsonData('录入的代金卡与申领单代金卡类型不匹配:'.implode(",",$err_array).$last_str, 404);
                    //没申请该卡
                }

            }

        }

        //循环申领单现金卡，检查录入的现金卡是否匹配
        foreach($apply_card_detail_array as &$apply_card_detail) {
            if ($apply_card_detail['face_value'] != $card_detail_array[0]['face_value']) {
                continue;
            }
            if ($apply_card_detail['card_num'] - $apply_card_detail['send_card_num'] < $card_num) {
                continue;
            }
            $return_array = array(
                'card_num' => $card_num,
                'face_value_id' => $apply_card_detail['face_value_id'],
                'face_value' => $apply_card_detail['face_value'],
                'card_spec' => $apply_card_detail['card_spec']
            );
            break;
        }


        if (empty($return_array)) {
            returnJsonData('录入的现金卡与申领单现金卡不匹配', 404);
        }

        returnJsonData('ok', 200, $return_array);

    }

    //申领单发票
    private function outInvoiceCard(){

        global $G_PGLOB;

        $_REQUEST['operator'] = $G_PGLOB->currentUserID;

        //实例化申领单类
        $cardApply = new cardApply() ;

        $result = $cardApply->outInvoiceCard($_REQUEST);

        if ($result['code'] == 200) {
            returnJsonData( $result['message'], $result['code'], $result['data'] );
        } else {
            returnJsonData( $result['message'], $result['code'] );
        }

    }

    //申领单确认开票
    private function confirmInvoice() {

        //实例化申领单类
        $cardApply = new cardApply() ;

        $result = $cardApply->confirmInvoice($_REQUEST);

        returnJsonData($result['message'], $result['code'] );

    }

    /**
     * 查询销售人员
     */
    private function searchSaler () {


        global $G_SHOP;

        $sysUser = new sysUser($G_SHOP->DBCA);//实例用户类

        if( isset($_REQUEST['departmentID']) && !is_numeric( $_REQUEST['departmentID'] )){
            returnJsonData('参数错误',404);
        }

        //实例化部门类
        $sysDepartment = new sysDepartment();

        //部门数据
        $department_array = array();
        //递归查询部门数据
        $sysDepartment->searchDepartment( $department_array,0,-1,$_REQUEST['departmentID']);

        //递归获得多维数组（部门id）的方法
        function getKey( $array , &$foreachKey_array){

            if( is_array( $array )){
                foreach( $array as $k=>$v){
                    if( $k == "departmentID"){
                        $foreachKey_array[] = $v;
                    }

                    if( is_array( $v )){
                        getKey( $v, $foreachKey_array );
                    }
                }
            }
        }


        $departmentKeyArray = array();

        getKey( $department_array, $departmentKeyArray );


        if( $departmentKeyArray ){ //当前登录用户权限下部门
            $str_departmentID = implode( ',',$departmentKeyArray );
            $_REQUEST['extend'] = " AND departmentID IN ( ".$str_departmentID." )";
        }

        $arg_array = array(
            'useFlg' => 1,
            'isSalesman' => 1,
            'extend'=>$_REQUEST['extend']
        );


        $user_array = $sysUser->searchUserInfo( $arg_array );

        returnJsonData( 'ok', 200, $user_array );

    }

    //申领单回款
    private function returnedMoney(){

        global $G_PGLOB;

        $_REQUEST['operator'] = $G_PGLOB->currentUserID;

        //实例化申领单类
        $cardApply = new cardApply() ;

        $result = $cardApply->returnedMoney($_REQUEST);

        if ($result['code'] == 200) {
            returnJsonData( $result['message'], $result['code'], $result['data'] );
        } else {
            returnJsonData( $result['message'], $result['code'] );
        }

    }

    //申领单确认回款
    private function confirmReturned() {

        //实例化申领单类
        $cardApply = new cardApply() ;

        $result = $cardApply->confirmReturned($_REQUEST);

        returnJsonData($result['message'], $result['code'] );

    }
    //删除申领单
    private function delReturned(){
        global $G_PGLOB;

        try{
            $G_PGLOB->DBCA->beginTransaction();

            //查询回款金额
              $applySql="select returned_amount,apply_id from card_apply_returned_money where returned_id= ?";
              $array= $G_PGLOB->DBCA->stmt_query($applySql,'i',$_REQUEST['returned_id']);
            //此条回款金额
             $monery=$array[0]->returned_amount;
            //对应的回款单ID
            $apply_id=$array[0]->apply_id;
            //回款金额
            $apply_Sql="select returned_amount  from card_apply where apply_id= ?";
            $ssymonery= $G_PGLOB->DBCA->stmt_query($apply_Sql,'i',$apply_id);
            //回款金额
            $ssymonery=$ssymonery[0]->returned_amount;

            //减少相应的申领单回款金额
            $apply=new entity('card_apply');
            $apply->apply_id=$apply_id;
            $G_PGLOB->DBCA->fetch($apply);
            $apply->returned_amount=$ssymonery-$monery;
            $G_PGLOB->DBCA->save($apply);


            //删除回款记录
              $delSql="delete from card_apply_returned_money where returned_id= ?";
              $rest= $G_PGLOB->DBCA->stmt_query($delSql,'i',$_REQUEST['returned_id']);
            $G_PGLOB->DBCA->commit();
            if($rest==1){
                die(json_encode(array('code' => 200, 'message' => '删除成功')));
            }else{
                die(json_encode(array('code' => 400, 'message' => '删除失败')));
            }

        } catch (Exception $e) {
            $G_PGLOB->DBCA->rollBack();
            die(json_encode(array('code' => 400, 'message' => '删除失败')));
        }



    }

    //申领单详情
    private function tuckCardDetails(){

        global $G_PGLOB;

        if( !isset($_REQUEST['apply_id']) || !quanli_is_int($_REQUEST['apply_id'])){
            returnJsonData('参数错误',404);
        }

        //实例申领单类
        $cardApply = new cardApply();

        //查询申领单信息
        $arg_array = array(
            'apply_id' => $_REQUEST['apply_id']
        );

        $cardApply_array = $cardApply->search( $arg_array );

        if($cardApply_array){

            //查询现金卡信息
            $arg_array = array(
                'apply_id' => $_REQUEST['apply_id']
            );

            $card_apply_detail_array = $cardApply->searchCardApplyDetail( $arg_array );

            if($card_apply_detail_array){
                $cardApply_array[0]['detail'] = $card_apply_detail_array;
            }else{
                $cardApply_array[0]['detail']  = "";
            }

            //add by dongleixin 查询发卡日志信息 start
            quanli_include('module/base/customer/logHandler.class.php');

            //实例日志类
            $logHandler = new logHandler( $G_PGLOB->DBCA );

            //订单操作记录
            $arg_array['logCategoryID'] = 14;
            $arg_array['logItem'] = $_REQUEST['apply_id'];
            $card_apply_array = $logHandler->searchLogInfo( $arg_array );

            if($card_apply_array){
                $cardApply_array[0]['apply'] = $card_apply_array;
            }else{
                $cardApply_array[0]['apply'] = "";
            }
            //add by dongleixin 查询发卡日志信息 end
            returnJsonData("ok",200,$cardApply_array[0]);

        }else{
            returnJsonData("申领卡信息不存在",400);
        }
    }

}
